package com.me.customerdemo.controller;

import com.github.pagehelper.PageInfo;

import com.me.customerdemo.pojo.Customer;
import com.me.customerdemo.service.CustomerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class CustomerController {

    // 初始化一个在当前类中使用的日志输出器
    private static Logger logger = LoggerFactory.getLogger(CustomerController.class);

    // @Autowired注解所标注的成员变量 其取值是由Spring框架创建的
    @Autowired
    CustomerService customerService;
    @GetMapping("/customer/customer_add")
    public ModelAndView customerAddView(){
        final ModelAndView mav = new ModelAndView("customer/customer_add");
        return mav;
    }

    @GetMapping("/customer/customer_list")
    public ModelAndView customerListView(
            @RequestParam(name = "pageNum",required = true,defaultValue = "1") int pageNum,
            @RequestParam(name = "pageSize",required = true,defaultValue = "5") int pageSize,
            @RequestParam(name = "keyword",required = false ) String keyword
    ){
        //int a = 1/0;
        final ModelAndView mav = new ModelAndView("customer/customer_list");
        // 分页查询数据
//        PageInfo<Customer> page= customerService.findAll(pageNum,pageSize);
        PageInfo<Customer> page = customerService.findByKeyword(pageNum,pageSize,keyword);
        mav.addObject("page",page);
        mav.addObject("keyword",keyword);
        return mav;
    }

    @GetMapping("/customer/customer_modify")
    public ModelAndView customerModifyView(
            @RequestParam(name = "id",required = true) int id
//            @RequestParam(name = "pageSize",required = false,defaultValue = "5") int pageSize,
//            @RequestParam(name = "pageNum",required = false,defaultValue = "1") int pageNum
    ){
        ModelAndView mav = new ModelAndView("/customer/customer_modify");
        // 查询要编辑的客户信息 并将它装入到环境
        Customer customer = customerService.findById(id);
        mav.addObject("customer",customer);
        return mav;
    }

    @PostMapping("/customer/customer_add")
    // @Validated注解标注的命令对象 表明该对象中的属性必须按照已定义的规则进行验证
    // BindingResult参数中封装了有关验证的信息 重点是包含了那些字段出错 以有相应的错误信息
    public ModelAndView customerAdd(@Validated Customer customer, BindingResult bindingResult){
        ModelAndView mav = new ModelAndView("redirect:/customer/customer_add");
        // 验证Customer实例中的每一个属性字段值是否符合规则
        // 如果符合规则 则保存数据 返回正常的视图
        // 如果不符合规则 则返回错误信息添加视图

        // 1. 编写验证代码
        // 2. 给视图环境添加错误信息及错误的字段
        // 3. 返回添加的页面 同时还要在页面上显示用户刚填写的内容

        Map<String,String> errors = new HashMap<>();
        if (bindingResult.hasErrors()){
            // 取出错误对象
            final List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            // 取出发生错误的字段名称及相应的错误信息 放入到映射集合中 用于发送到视图环境
            for (FieldError error : fieldErrors){
                // 从错误对象中取出相应的字段名称作为键 对应的错误信息作为值 放入到映射集合中
                errors.put(error.getField(),error.getDefaultMessage());
            }
            mav.addObject("errors",errors);
            mav.addObject("customer",customer);
            mav.setViewName("customer/customer_add");
        }else{
            boolean result = customerService.apply(customer);
            if (result){
                logger.info("管理员***，成功添加一个新客户 - " + customer);
            }else {
                logger.error("管理员***，新增客户信息失败 - " + customer);
            }
        }

        // 调用服务层方法来保存数据
//        customerService.apply(customer);
        return mav;
    }

    @PostMapping("/customer/customer_modify")
    public ModelAndView customerModify(
            Customer customer,
            @RequestParam(name = "pageSize",required = false,defaultValue = "5") int pageSize,
            @RequestParam(name = "pageNum",required = false,defaultValue = "1") int pageNum,
            @RequestParam(name = "keyword",required = false) String keyword

    ) throws UnsupportedEncodingException {
        String redirectUrl = "redirect:/customer/customer_list?pageSize=" + pageSize + "&pageNum=" + pageNum + "&keyword=" + (keyword == null? "" : URLEncoder.encode(keyword,"utf-8"));
        ModelAndView mav = new ModelAndView(redirectUrl);
        // 调用服务层 保存客户信息
        boolean result = customerService.modify(customer);
        return mav;
    }

    @GetMapping("/customer/customer_remove")
    public ModelAndView customerRemove(
            @RequestParam(name = "id",required = true) int id,
            @RequestParam(name = "pageSize",required = false,defaultValue = "5") int pageSize,
            @RequestParam(name = "pageNum",required = false,defaultValue = "1") int pageNum,
            @RequestParam(name = "keyword",required = false) String keyword
    ) throws UnsupportedEncodingException {
        String redirectUrl = "redirect:/customer/customer_list?pageSize=" + pageSize + "&pageNum=" + pageNum + "&keyword=" + (keyword == null? "" : URLEncoder.encode(keyword,"utf-8"));
        ModelAndView mav = new ModelAndView(redirectUrl);
        // 调用服务层 保存客户信息
        boolean result = customerService.removeById(id);
        if (result){
            logger.info("管理员***，成功删除一个新客户 - " + id);
        }else {
            logger.error("管理员***，删除客户信息失败 - " + id);
        }
        return mav;
    }
}
